package com.xsy.de.controller;


import com.xsy.de.entity.Texts;
import com.xsy.de.entity.User;
import com.xsy.de.service.TextsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DingHao
 * @since 2019-06-20
 */
@Controller
@RequestMapping("/texts")
public class TextsController {

    @Autowired
    TextsService textsService;

    @PostMapping(value = "/submit")
    @ResponseBody
    public String submitText(String title, String body, HttpServletRequest request){
        try {
            Texts texts = new Texts();
            texts.setTitel(title);
            texts.setBody(body);
            texts.setCreateDate(LocalDateTime.now());
            texts.setModifyDate(LocalDateTime.now());
            User user = (User) request.getSession().getAttribute("user");
            texts.setUserId(user.getId());
            if (textsService.insert(texts)){
                return "SUCCESS";
            }else {
                return "FAIL: inser database fail";
            }
//            return "SUCCESS";
        }catch (Exception e){
            e.printStackTrace();
            return "FAIL:"+e.getMessage();
        }
    }

    @RequestMapping(value = "/edit/{id}")
    public String toEditPage(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response, ModelMap model){
        try {
            String login = request.getSession().getAttribute("login").toString();
            if (!"Y".equals(login)){
                return "redirect:/login";
            }
        }catch (Exception e){
            return "redirect:/login";
        }
        Texts texts = null;
        try {
            texts = (Texts) textsService.selectById(id);
        }catch (Exception e){
            e.printStackTrace();
            return "error/404";
        }
        if (texts != null){
            model.addAttribute("title",texts.getTitel());
            model.addAttribute("userId",texts.getUserId());
            model.addAttribute("body",texts.getBody());
            model.addAttribute("creatDate",texts.getCreateDate());
            model.addAttribute("modifyDate",texts.getModifyDate());
        }else {
            return "error/404";
        }
        return "editPage";
    }
}

